package com.rainbow.redis.plus.core.monitor;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.annotation.PostConstruct;

import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;

import com.rainbow.redis.plus.core.constant.RedisConstant;
import com.rainbow.redis.plus.core.entity.BlackTagEntity;
import com.rainbow.redis.plus.core.utils.JsonUtils;

public class BlackTagService implements EnvironmentAware {
	//是否此项目进入黑名单，不让请求redis
	private boolean black = false;
	
	private Environment environment;
	
	private String projectName;
	
	private String localInstanceIp;
	
	private Integer localInstancePort;
	
	public boolean isBlack() {
		return black;
	}

	public void setBlack(boolean black) {
		this.black = black;
	}

	public String getProjectName() {
		if (projectName == null) {
			projectName = environment.getProperty(RedisConstant.PROJECT_NAME, String.class, "");
		}
		return projectName;
	}
	
	@PostConstruct
	public void init() {
		getProjectName();
		getLocalInstanceIp();
		getLocalInstancePort();
	}
	
	public String getLocalInstanceIp() {
		if (localInstanceIp == null) {
			InetAddress address;
			try {
				address = InetAddress.getLocalHost();
				localInstanceIp = address.getHostAddress(); //返回IP地址
			} catch (UnknownHostException e) {
				localInstanceIp = "";
				e.printStackTrace();
			}
		}
		return localInstanceIp;
	}
	
	public Integer getLocalInstancePort() {
		if (localInstancePort == null) {
			localInstancePort = environment.getProperty(RedisConstant.SERVER_PORT, Integer.class, 80);
		}
		return localInstancePort;
	}
	
	public void parseBlackTag(String message) {
		try {
			BlackTagEntity blackTagEntity = JsonUtils.json2Object(message, BlackTagEntity.class);
			if (blackTagEntity != null && projectName.equals(blackTagEntity.getProjectName())) {
				this.setBlack(blackTagEntity.getBlackTag());
			}
			if (blackTagEntity != null && localInstanceIp.equals(blackTagEntity.getInstanceIp())
					&& localInstancePort.equals(blackTagEntity.getInstancePort())) {
				this.setBlack(blackTagEntity.getBlackTag());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void setEnvironment(Environment environment) {
		this.environment = environment;
	}
}
